import { observer } from 'mobx-react-lite';
import React, { useState, useRef, useEffect } from 'react';
import { Drawer, Form, Button, Dialog, Tag, Notification, Input, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import * as dict from '@/services/dict';
import DrawerFooter from '@/components/DrawerFooter';
import { TitleGrid, FieldsGrid, ENUMS } from '../../stores/definitions';
import { column, DATE_TEXT } from '../../stores/definitions_order';
import { useStore } from '@/hooks';
import { observable } from 'mobx';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import TauTable from '@/components/TauTable';
import TicketTable from '../TicketTable';

const FromItem = Form.Item;

const Index = ({ visible, task, onCancel, modal, onSubmit }) => {
  const { scTaskStore: store } = useStore();
  const [alteration] = useState(() => observable({}));
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [companys, setCompanys] = useState([]);
  const opCompaniesRef = useRef(null);
  const [currentTicket, setCurrentTicket] = useState(false);

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (modal[0] === 'alteration') {
      if (JSON.stringify(task) !== '{}') {
        const data = task;
        (async () => {
          await store.getNoticeUsers();
          const { startMainArea, endMainArea, tickets } = task;
          const { fromStation, toStation } = tickets[0];
          await store.getStartBusStation({ fromCities: [startMainArea], toCities: [endMainArea], direction: 0, priceType: '3' });
          const companies = await store.taskListCompany({ taskId: data?.id, orderIds: data.orderIds, status: '1' });
          setCompanys(() => companies.map(({ name, id }) => ({ label: name, value: id })));
          const res = await store.getPrices({
            priceType: '2',
            startMainArea,
            endMainArea,
            startMinorAreas: [fromStation],
            endMinorAreas: [toStation],
          });
          const { automaticTicketIssue } = res[0] || {};
          // 是否有出过票
          const currentTicketStatus = tickets.some((p) => !p.operatingTicketCode || (!p.errorMsg && p.errorMsg !== ''));
          await init(data, false, currentTicketStatus, automaticTicketIssue);
        })();
      }
    }
    return (() => {
      rest(['arCarrierCompanyId', 'arCarrierCompanyPrice', 'arCarrierCompanyName',
        'remark', 'dispatchOrderRemarks', 'startMinorArea', 'endMinorArea', 'serviceShift',
        'noticeUser',
      ]);
      store.selectSettled = [];
      store.noticeUsers = [];
      store.startStations = [];
      store.endStations = [];
      store.shifts = [];
      setCurrentTicket(false);
    });
  }, [task]);

  /**
   * 初始化操作，重新赋值数据，更新车票信息
   * @param {*} data 数据源
   * @param {*} ZGTTakeTicket 是否中港通
   * @param {*} take
   * @param {*} automaticTicketIssue 关联信息
   */
  async function init(data, ZGTTakeTicket, take, automaticTicketIssue, stationInfo) {
    try {
      const taskInfo = await store.getTaskInfo(data?.id);
      const res = await store.transferCompanies({ isOperating: true });
      const orders = await store.getScOrders({ orderIds: task.orderIds });
      const dicts = await dict.searchDictItem('zgtInfo');
      const companyInfo = dicts.find((p) => p.itemId === 'automaticCompanyId');
      opCompaniesRef.current = res;
      _.assign(alteration, { ...taskInfo, orders, ZGTTakeTicket, ...stationInfo });
      editCtx.origin = _.cloneDeep(taskInfo);
      if (!ZGTTakeTicket) {
        _.set(alteration, 'startMinorArea', '');
        _.set(alteration, 'endMinorArea', '');
        if (!take) {
          const {
            onStationId,
            offStationId,
            user,
          } = automaticTicketIssue || {};
          _.set(alteration, 'startMinorArea', onStationId);
          _.set(alteration, 'endMinorArea', offStationId);
          _.set(alteration, 'arCarrierCompanyId', companyInfo?.name);
          _.set(alteration, 'noticeUser', user?.mobile);
          await store.getEndBusStation({
            fromCities: [alteration.startMainArea],
            toCities: [alteration.endMainArea],
            fromStation: onStationId,
            direction: 1,
            priceType: '3',
          });
          await getServiceShifts(offStationId);
        }
      }
    } catch (error) {
      console.log('🚀 _ init _ error:', error);
      throw error;
    }
  }

  function rest(files) {
    for (const e of files) {
      _.set(alteration, e, '');
    }
  }

  // 自定义标题
  const titleElement = (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <div style={{ marginRight: 10 }}>{t`任务【${task?.id}】变更`}</div>
      <Tag type="normal" color="blue" size="small">
        {ENUMS.states[task?.state]}
      </Tag>
    </div>
  );

  const overrideModel = {
    arCarrierCompanyId: {
      label: t`承运公司`,
      ui: {
        renderer: (v) => {
          return <TauSimpleSelect data={companys} value={v} onChange={handleArCompany} />;
        },
        itemProps: {
          required: true,
        },
      },
    },
    dispatchOrderRemarks: {
      ui: {
        renderer: (v) => <Input.TextArea value={v} placeholder={t`给公司调度留言`} />,
        itemProps: {
          required: false,
        },
      },
    },
    endMinorArea: {
      ui: {
        itemProps: { required: false },
      },
    },
    startMinorArea: {
      ui: {
        itemProps: { required: false },
      },
    },
    serviceShift: {
      ui: {
        itemProps: { required: false },
      },
    },
    noticeUser: {
      ui: {
        itemProps: { required: false },
      },
    },
  };

  const handleArCompany = (v, __, e) => {
    if (v) {
      const { label } = e;
      _.set(alteration, 'arCarrierCompanyName', label);
    } else {
      _.set('arCarrierCompanyName', '');
    }
  };

  const handleChange = async (values, item) => {
    const { name, value } = item;
    _.set(alteration, name, value);
    if (name === 'ZGTTakeTicket') {
      setCurrentTicket(value);
    }
    if (name === 'startMinorArea') {
      await store.getEndBusStation({
        fromCities: [alteration.startMainArea],
        toCities: [alteration.endMainArea],
        fromStation: value,
        direction: 1,
        priceType: '3',
      });
      _.set(alteration, 'endMinorArea', '');
      _.set(alteration, 'serviceShift', '');
      // eslint-disable-next-line require-atomic-updates
      store.shifts = [];
    }
    if (name === 'endMinorArea') {
      await getServiceShifts(value);
    }
    if (name === 'serviceShift') {
      const shift = item?.field?.fieldsMeta[name]?.inputValues?.[2];
      _.set(alteration, 'shift', shift);
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  async function getServiceShifts(offStationId) {
    try {
      await store.getServiceShifts({
        onStationId: alteration.startMinorArea,
        offStationId,
        departureDate: DATE_TEXT(alteration.departureTime),
        currency: 'HKD',
        account: 'HKD',
        isReturn: '0',
        companyId: global?.getEnvCfg()?.companies?.ZGT?.id,
        ticketType: '0',
        orderType: '3',
      });
    } catch (error) {
      Message.error({ content: t`请求失败 ${error?.message}` });
      throw error;
    }
  }

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('...errors', errors);
      return;
    }
    if (currentSendCar(alteration)) return;
    // https://pm.aspiretop.com/issues/5200
    // https://pm.aspiretop.com/issues/5208
    let isValid = true;
    const { startMinorArea, endMinorArea, arCarrierCompanyPrice, totalPrice, tickets = [] } = toJS(alteration);
    if (Number(arCarrierCompanyPrice) > Number(totalPrice)) {
      isValid = false;
    }
    const _tickets = _.cloneDeep(tickets);
    const ticketsTake = tickets.filter((p) => !p.operatingTicketCode);
    const ticketsTakeOk = tickets.filter((p) => p.operatingTicketCode);
    if (ticketsTakeOk.length === _tickets.length) {
      Message.error({ content: t`已经全部出票成功，不可重复出票！` });
      return;
    }
    Dialog.confirm({
      // eslint-disable-next-line no-nested-ternary
      content: isValid ? (alteration.ZGTTakeTicket ? t`本次出票${ticketsTake?.length}张，确认出票吗？` : t`确定变更吗？`) : t`公司价格超过任务总价, 是否继续变更？`,
      onOk: async () => {
        if (alteration.ZGTTakeTicket) {
          try {
            const {
              arCarrierCompanyId, arCarrierCompanyName,
              id, noticeUser, shift, dispatchOrderRemarks = '',
            } = toJS(alteration);
            if (!shift && !noticeUser) {
              Message.error({ content: t`请补全信息！` });
              return;
            }
            const filterTickets = _tickets.filter((p) => (!p.operatingTicketCode) || (p.operatingTicketCode === ''));
            const params = {
              carrierCompany: arCarrierCompanyId,
              carrierCompanyName: arCarrierCompanyName,
            };
            const user = await store.getUserInfo(noticeUser);
            _.assign(params, {
              taskId: id,
              user: {
                ...user,
              },
              tickets: filterTickets,
              otherShift: shift,
              dispatchOrderRemarks,
            });
            await store.servicesTicketIssue(params);
            Message.success({ content: t`线下出票成功` });
          } catch (e) {
            Message.error({ content: t`线下出票失败: ${e?.source?.message}`, duration: 7000 });
            throw e;
          } finally {
            // 第五个参数防止任务里面的上下车站点覆盖已输入数据
            await init(task, true, false, {}, { startMinorArea, endMinorArea });
          }
        } else {
          onSubmit?.(alteration);
        }
      },
    });
  };

  function currentSendCar(params) {
    const info = params;
    let result = false;
    if (info?.driverInfo && JSON.stringify(info?.driverInfo) !== '{}') {
      const drivers = info?.driverInfo;
      for (let i = 0; drivers < drivers.length; i++) {
        const element = drivers[i];
        if (element?.state !== '0') {
          result = true;
          Notification.open({
            title: '警告⚠️',
            content:
              t`当前任务正在进行, 司机是【${element?.name}】`,
            type: 'warning',
          });
        }
      }
    }
    return result;
  }

  return (
    <Drawer
      visible={visible}
      title={titleElement}
      onClose={handleCancel}
      closeMode={['esc', 'mask', 'close']}
      style={{ maxWidth: '100%' }}
      width="90%"
    >
      <Form
        inline
        isPreview={isViewMode}
        {...formProps}
        value={alteration}
        onChange={handleChange}
        useLabelForErrorMessage
      >
        <TitleGrid title={t`任务信息`} />
        <FieldsGrid
          formData={alteration}
          mode={'view'}
          fields={[
            'id', 'crDate',
            'orderBaseModel.subscribeName',
            'orderBaseModel.subscribePhone',
            'orderBaseModel.predictBeginDate',
            'orderBaseModel.predictEndDate',
            'orderBaseModel.portTypeText',
            'orderBaseModel.mileage',
            'orderBaseModel.startMainAreaText',
            'orderBaseModel.startStationName',
            'orderBaseModel.endMainAreaText',
            'orderBaseModel.endStationName',
            'orderBaseModel.beginName',
            'orderBaseModel.endName',
          ]}
        />
        <TitleGrid title={t`承运及费用信息`} />
        <FieldsGrid
          formData={alteration}
          mode={'view'}
          fields={['totalPrice', 'carrierCompanyName', 'departureTime', 'midwayFee']}
        />
        <TitleGrid title={t`变更信息`} />
        <div>
          <span style={{ color: 'red', fontWeight: 500 }}>{t`提示：相同订单在不同任务里，任务选择公司只能相同！`}</span>
        </div>
        <FieldsGrid
          formData={alteration}
          mode={modal[0]}
          overrideModel={overrideModel}
          fields={['ZGTTakeTicket']}
        />
        {currentTicket ?
          <>
            <TitleGrid title={(
              <>
                <span>{t`站点信息`}</span>
                <Form.Submit validate type="primary" style={{ marginLeft: 10 }} onClick={handleSubmit}>{alteration.tickets?.some((p) => p.errorMsg) ? t`继续出票` : t`出票`}</Form.Submit>
              </>
            )}
            />
            <FieldsGrid
              formData={alteration}
              mode="edit"
              overrideModel={overrideModel}
              fields={[
                'arCarrierCompanyId', 'startMinorArea', 'endMinorArea', 'serviceShift', 'noticeUser',
              ]}
            />
            <TitleGrid title={t`订单信息`} />
            <TauTable
              primaryKey="id"
              tableLayout="fixed"
              total={alteration?.orders?.length}
              dataSource={toJS(alteration?.orders)}
              hidePagination
              expandedRowRender={(row) => (
                <TicketTable
                  scOrder={row?.scOrder}
                  refundInfo={row?.applicationRefunds}
                  orderId={row?.id}
                  tickets={alteration?.tickets}
                />
              )}
              expandedRowIndent={[300, 100]}
              expandAll={false}
              // rowSelection={{
              //   onChange: (e, r) => handleSelectChange(e, r),
              //   columnProps: () => {
              //     return {
              //       lock: 'right',
              //       width: 38,
              //       align: 'center',
              //     };
              //   },
              // }}
              columns={[
                { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store._mainArgs.idx(i) },
                column('orderNumber', {
                  cell: (v, i, r) => {
                    const _ticket = store.transferTicketsError(alteration?.tickets, r);
                    return (
                      <>
                        <span style={{ color: _ticket.length > 0 ? 'red' : '' }}>{v}</span>
                        {_ticket.length > 0 && (
                          <>
                            <span style={{ margin: '0 3px' }}>{'/'}</span>
                            <span style={{ color: 'red' }}>{`${_ticket.length}`}</span>
                          </>
                        )}
                      </>
                    );
                  },
                }),
                column('price', {}),
                column('beginAreaName', {}),
                column('endAreaName', {}),
                column('scOrder.shiftTime', {}),
                column('crDate', {}),
              ]}
            />
          </> :
          <FieldsGrid
            formData={alteration}
            mode={modal[0]}
            overrideModel={overrideModel}
            fields={['arCarrierCompanyId', 'arCarrierCompanyPrice']}
          />}
        <FieldsGrid
          formData={alteration}
          mode={modal[0]}
          overrideModel={overrideModel}
          fields={['dispatchOrderRemarks']}
        />
        <DrawerFooter>
          <FromItem>
            {!isViewMode && !alteration.ZGTTakeTicket && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
            <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
          </FromItem>
        </DrawerFooter>
      </Form>
    </Drawer>
  );
};

export default observer(Index);
